package com.ruoyi.web.controller.ex;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.doudou.core.lang.Option;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.aliyun.MySms;
import com.ruoyi.ex.domain.ExQuestionBank;
import com.ruoyi.ex.domain.ExStudyReloadExcel;
import com.ruoyi.ex.service.ExService;
import com.ruoyi.ex.service.IExQuestionBankService;
import com.ruoyi.ex.service.IExQuestionService;
import com.ruoyi.pv.domain.PvStudentRecord;
import com.ruoyi.pv.domain.PvUserInfo;
import com.ruoyi.pv.service.IPvStudentRecordService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ex.domain.ExStudyReload;
import com.ruoyi.ex.service.IExStudyReloadService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 考试报名记录Controller
 *
 * @author zzx
 * @date 2023-05-06
 */
@Api("考试报名记录")
@RestController
@RequestMapping("/pv/ex_study_reload")
public class ExStudyReloadController extends BaseController {

    @Autowired private IExStudyReloadService exStudyReloadService;
    @Autowired private IPvStudentRecordService studentRecordService;
    @Autowired private IExQuestionService questionService;
    @Autowired private ExService exService;
    @Autowired private IExQuestionService questionBankService;
//    @Autowired private MySms smsUtil;
    @Autowired private ISysUserService userService;
    @Autowired private IExQuestionBankService exQuestionBankService;



    /**
     * 查询考试报名记录列表
     */
    @PreAuthorize("@ss.hasPermi('pv:ex_study_reload:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExStudyReload exStudyReload) {
        exStudyReload.setDeptId(getDeptId());
        startPage();
        List<ExStudyReload> list = exStudyReloadService.selectExStudyReloadList(exStudyReload);
        return getDataTable(list);
    }


    /**
     * 查询当前用户的考试报名记录列表
     */
    @GetMapping("/my-list")
    public TableDataInfo myList() {
        //TODO
        ExStudyReload exStudyReload = ExStudyReload.builder().deptId(getDeptId()).stuId(getUserId()).build();
        return getDataTable(exStudyReloadService.selectExStudyReloadList(exStudyReload));
        //return getDataTable(ListUtil.list(false));
    }

    /**
     * 导出考试报名记录列表
     */
    @PreAuthorize("@ss.hasPermi('pv:ex_study_reload:export')")
    @Log(title = "考试报名记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExStudyReload exStudyReload) {
        exStudyReload.setDeptId(getDeptId());
        List<ExStudyReload> list = exStudyReloadService.selectExStudyReloadList(exStudyReload);
        ExcelUtil<ExStudyReload> util = new ExcelUtil<>(ExStudyReload.class);
        util.exportExcel(response, list, "考试报名记录数据");
    }

    /**
     * 导出考试报名记录列表
     */
    @PreAuthorize("@ss.hasPermi('pv:ex_study_reload:export')")
    @Log(title = "考试报名记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export-ex")
    public void exportEX(HttpServletResponse response, ExStudyReload exStudyReload) {
        exStudyReload.setDeptId(getDeptId());
        List<ExStudyReload> list = exStudyReloadService.selectExStudyReloadList(exStudyReload);
        List<ExStudyReloadExcel> collect = list.stream().map(ExStudyReloadExcel::new)
                .sorted(Comparator.comparing(e-> Option.of(e.getScore()).get(0D))).collect(Collectors.toList());
        ExcelUtil<ExStudyReloadExcel> util = new ExcelUtil<>(ExStudyReloadExcel.class);
        util.exportExcel(response, collect, "考试报名记录数据");
    }

    /**
     * 获取考试报名记录详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ExStudyReload exStudyReload = exStudyReloadService.selectExStudyReloadById(id);
        if (exStudyReload.getStatus().equals(3)){
            Map<Long, Boolean> questionAnswers = new HashMap<>();
            //格式化已回答列表
            List<Long> questionIds = questionBankService.selectIdsByBankId(exStudyReload.getBankId());
            Map<Long, Object> answerMap = exService.rightTotal(exStudyReload.getAnswerMap(),questionIds);
            for (Long questionId : questionIds) {
                questionAnswers.put(questionId,answerMap.containsKey(questionId));
            }
            exStudyReload.setQuestionAnswers(questionAnswers);
        }
        return success(exStudyReload);
    }

    /**
     * 获取当前登录用户考试报名记录详细信息
     */
    @ApiOperation("获取考试报名记录详细信息")
    @GetMapping(value = "/student")
    public AjaxResult getStudentInfo() {
        ExStudyReload build = ExStudyReload.builder().stuId(getUserId()).deptId(getDeptId()).build();
        List<ExStudyReload> exStudyReloads = exStudyReloadService.selectExStudyReloadList(build);
        if (ObjectUtil.isNotEmpty(exStudyReloads)){
            build = exStudyReloads.get(0);
            if (build.getStatus().equals(3)){
                Map<Long, Boolean> questionAnswers = new HashMap<>();
                //格式化已回答列表
                List<Long> questionIds = questionBankService.selectIdsByBankId(build.getBankId());
                Map<Long, Object> answerMap = exService.rightTotal(build.getAnswerMap(),questionIds);
                for (Long questionId : questionIds) {
                    questionAnswers.put(questionId,answerMap.containsKey(questionId));
                }
                build.setQuestionAnswers(questionAnswers);
            }
            //对题数和分数为 null 时说明未提交
            return success().put("data",ObjectUtil.isAllEmpty(build.getRight(),build.getScore()) ? build : null);
        }else{
            return success().put("data",null);
        }
    }

    /**
     * 新增考试报名记录
     */
    @ApiOperation("新增考试报名记录")
    @Log(title = "考试报名记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ExStudyReload exStudyReload) {
        //获取当前登录用户的权限
        PvUserInfo userInfo = getUserInfo(PvUserInfo.class);
        //查询是否是初训
        PvStudentRecord pvStudentRecord = studentRecordService.thisYearHas(userInfo.getId());
        if (ObjectUtil.isEmpty(pvStudentRecord)){
            return AjaxResult.error("未查询到报名记录，请先前往主页报名");
        }
        if (exStudyReload.getExDate() == null || exStudyReload.getExTimeObj().isEmpty()){
            return AjaxResult.error("请选择考试日期和时间");
        }
        ExQuestionBank build = ExQuestionBank.builder().
                classId(pvStudentRecord.getTraining()).//培训班
                deptId(getDeptId()).
                trainFlag(Integer.valueOf(userInfo.getReservedOne())).//初复训
                status(0).build();
        List<ExQuestionBank> questionBank = exQuestionBankService.selectExQuestionExList(build);
        //List<ExQuestionBank> questionBanks = exQuestionBankService.selectExQuestionEx(ExQuestionBank.builder().deptId(getDeptId()).build());
        //exStudyReload.setIsFirst(pvStudentRecords.size()+1);
        exStudyReload.setBankId(questionBank.get(0).getId());
        exStudyReload.setStuId(userInfo.getId());
        exStudyReload.setDeptId(getDeptId());
        exStudyReload.setStatus(1);
        return toAjax(exStudyReloadService.insertExStudyReload(exStudyReload));
    }

    /**
     * 修改考试报名记录
     */
    @ApiOperation("提交考试报名记录")
    @Log(title = "考试报名记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExStudyReload exStudyReload) {
        if (exStudyReload.getStatus().equals(3)){
            List<Long> questionIds = questionService.selectIdsByBankId(exStudyReload.getBankId());
            Map<Long, Object> answerMap = exService.rightTotal(exStudyReload.getAnswerMap(),questionIds);
            //计算对题
            int size = answerMap.size();
            exStudyReload.setRight(size);
            exStudyReload.setScore(NumberUtil.round((double) size / questionIds.size() * 100,2).doubleValue());
        }
        int i = exStudyReloadService.updateExStudyReload(exStudyReload);
//        if (i > 0 && exStudyReload.getStatus().equals(1)){//审核通过，发送短信
//            //查询题库信息
//            //List<ExQuestionBank> questionBanks = exQuestionBankService.selectExQuestionEx(ExQuestionBank.builder().deptId(getDeptId()).build());
//            //exStudyReload.setBankId(questionBanks.get(0).getId());
//            ExQuestionBank questionBank = exQuestionBankService.selectExQuestionBankById(exStudyReload.getBankId());
//            //查询用户信息
//            SysUser sysUser = userService.selectUserById(exStudyReload.getStuId());
//            //发送短信
//            try{
//                String time = exStudyReload.getExTimeObj().getJSONArray("time").getStr(0);
//                smsUtil.sendExApply(sysUser.getPhonenumber(),
//                        sysUser.getNickName(), questionBank.getName(),
//                        DateUtil.format(exStudyReload.getExDate(), "yyyy-MM-dd"), time);
//            }catch (Exception e){
//                logger.info("发送短信失败",e);
//            }
//        }
        //更新用户合格状态
        studentRecordService.updateQualified(studentRecordService.thisYearHas(getUserId()).getId());
        return toAjax(i).put("score",exStudyReload.getScore());
    }

    /**
     * 删除考试报名记录
     */
    @PreAuthorize("@ss.hasPermi('pv:ex_study_reload:remove')")
    @Log(title = "考试报名记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(exStudyReloadService.deleteExStudyReloadByIds(ids));
    }
}
